package top.tangyh.lamp.care.controller;

import cn.hutool.core.collection.CollectionUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.BatchResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.tangyh.basic.base.R;
import top.tangyh.basic.context.ContextUtil;
import top.tangyh.basic.interfaces.echo.EchoService;
import top.tangyh.basic.base.controller.SuperController;
import top.tangyh.lamp.care.entity.BHl7Event;
import top.tangyh.lamp.care.entity.BTimePlan;
import top.tangyh.lamp.care.mapper.BTimePlanMapper;
import top.tangyh.lamp.care.service.BCareRecordsConfigNewOneService;
import top.tangyh.lamp.care.service.BCareRecordsConfigNewService;
import top.tangyh.lamp.care.entity.BCareRecordsConfigNew;
import top.tangyh.lamp.care.service.BTimePlanService;
import top.tangyh.lamp.care.vo.query.DeleteBactchQuery;
import top.tangyh.lamp.care.vo.result.CartPgpfTempOutVO;
import top.tangyh.lamp.care.vo.save.BCareRecordsConfigNewSaveVO;
import top.tangyh.lamp.care.vo.save.CareRecordDataVO;
import top.tangyh.lamp.care.vo.save.CareRecordsConfigSaveVO;
import top.tangyh.lamp.care.vo.save.TimePlanInVO;
import top.tangyh.lamp.care.vo.update.BCareRecordsConfigNewUpdateVO;
import top.tangyh.lamp.care.vo.result.BCareRecordsConfigNewResultVO;
import top.tangyh.lamp.care.vo.query.BCareRecordsConfigNewPageQuery;
import top.tangyh.lamp.care.vo.update.CareRecordsConfigUpdateVO;
import top.tangyh.lamp.common.utils.PDateUtils;
import top.tangyh.lamp.common.utils.YDateUtils;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * 新版本护理记录表单配置表
 * </p>
 *
 * @author zqb
 * @date 2024-08-05 15:12:19
 * @create [2024-08-05 15:12:19] [zqb] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/care/config")
@Tag(name = "系统：文书-重症护理单-护理记录配置")
public class BCareRecordsConfigNewController {
//    extends SuperController<BCareRecordsConfigNewService, Long, BCareRecordsConfigNew
//            , BCareRecordsConfigNewSaveVO, BCareRecordsConfigNewUpdateVO, BCareRecordsConfigNewPageQuery, BCareRecordsConfigNewResultVO>
//    private final EchoService echoService;
//    @Override
//    public EchoService getEchoService() {
//        return echoService;
//    }

    private final BCareRecordsConfigNewService bCareRecordsConfigNewService;

    private final BCareRecordsConfigNewOneService bCareRecordsConfigNewOneService;

    private final BTimePlanService bTimePlanService;

    private final BTimePlanMapper bTimePlanMapper;


    @Operation(summary = "保存护理记录配置/")
    @PostMapping("/save")
    public R addNew(@Valid @RequestBody CareRecordsConfigSaveVO vo) {
        return R.success(bCareRecordsConfigNewService.saveCareRecordsConfigNew(vo));
    }


    @Operation(summary = "批量保存护理记录配置/")
    @PostMapping("/batch/save/new")
    public R addBatchNew(@Valid @RequestBody List<CareRecordsConfigSaveVO> vos) {
        return R.success(bCareRecordsConfigNewService.saveBatchCareRecordsConfigNew(vos));
    }


    @Operation(summary = "全局更新护理记录配置/")
    @PutMapping("/batch/update/new")
    public R BatchUpdate(@Valid @RequestBody List<CareRecordsConfigUpdateVO> listVo) {
        return R.success(bCareRecordsConfigNewService.batchUpdateCareRecordsConfigNew(listVo));
    }


    @Operation(summary = "删除护理记录配置/")
    @DeleteMapping("/delete/new")
    public R delete(Long id) {
        BCareRecordsConfigNew po = new BCareRecordsConfigNew();
        po.setId(id);
        po.setIsDeleted(1);
        BCareRecordsConfigNew result = bCareRecordsConfigNewService.updateById(po);

        List<BCareRecordsConfigNew> chids = bCareRecordsConfigNewService.getIdObjectByPid(id);
        chids.forEach(item -> item.setIsDeleted(1));
        bCareRecordsConfigNewService.updateBatchById(chids);
        return R.success(result);
    }


    @Operation(summary = "批量删除护理记录配置/")
    @DeleteMapping("batch/delete/new")
    public R<Boolean> deleteBatch(@RequestBody DeleteBactchQuery deleteBactchQuery) {
        List<Long> ids=deleteBactchQuery.getIds();
        List<BCareRecordsConfigNew> configPOList = new ArrayList<>();
        for (int i = 0; i < ids.size(); i++) {
            BCareRecordsConfigNew po = new BCareRecordsConfigNew();
            po.setId(ids.get(i));
            po.setIsDeleted(1);
            configPOList.add(po);

        }
        List<BatchResult> result = bCareRecordsConfigNewService.updateBatchById(configPOList);
        //
        //删除对应子集的数据
        for (int i = 0; i < ids.size(); i++) {
            List<BCareRecordsConfigNew> chids = bCareRecordsConfigNewService.getIdObjectByPid(ids.get(i));
            if (chids != null && !chids.isEmpty()) {
                chids.forEach(item -> item.setIsDeleted(1));
                bCareRecordsConfigNewService.updateBatchById(chids);
            }

        }

        return R.success(true);
    }


    @GetMapping("/list/new")
    @Operation(summary = "查询护理记录配置/")
    public R<List<BCareRecordsConfigNewResultVO>> list() {
        return R.success(bCareRecordsConfigNewService.listCareRecordsConfig());
    }


    @GetMapping("/list/tree/new")
    @Operation(summary = "读取全部配置管理内容-带树形/")
    public R<List<BCareRecordsConfigNewResultVO>> listTree() {
        return R.success(bCareRecordsConfigNewService.getAllcareConfig());
    }

    /**
     * @param hospitalNumber
     * @param startTime
     * @param endTime
     * @param isHistory      isHistory 0 历史模式 1在科模式
     * @return
     */


    @GetMapping("/list/title/tree/new")
    @Operation(summary = "重症护理单配置标题/")
    public R<List<BCareRecordsConfigNewResultVO>> listTitleTreeNew(@RequestParam(required = false) String patientIdent, @RequestParam String hospitalNumber, @RequestParam Long startTime, @RequestParam(required = false) Long endTime, @RequestParam(required = true) Integer isHistory) {
        if (null == startTime) {
            return R.fail("入科时间不能为空");
        } else {
            BHl7Event yxHl7EventPORk = new BHl7Event();
            yxHl7EventPORk.setEventTime(PDateUtils.getDateTimeOfTimestamp(startTime));
            return R.success(bCareRecordsConfigNewService.titleNoteTreeNew(patientIdent, hospitalNumber, yxHl7EventPORk));
        }

    }


    @GetMapping("/list/data/new")
    @Operation(summary = "重症护理单数据接口/")
    public R<List<Map.Entry<String, List<Map>>>> listOfDataNew(@RequestParam String patientIdent, @RequestParam String hospitalNumber
            , @RequestParam Long startTime, @RequestParam(required = false) Long endTime) {

        List<Map.Entry<String, List<Map>>> list = bCareRecordsConfigNewService.listOfDataNew(patientIdent, hospitalNumber, startTime, endTime);
        return R.success(list, "数据总数:" + list.size());
    }

    @GetMapping("/list/data/new/one")
    @Operation(summary = "重症护理单数据接口(指定时间点)/")
    public R<List<Map.Entry<String, List<Map>>>> listOfDataNewByTimeCode(@RequestParam String patientIdent, @RequestParam String hospitalNumber
            , @RequestParam Long recordTime) {

        List<Map.Entry<String, List<Map>>> list = bCareRecordsConfigNewOneService.listOfDataNewOne(patientIdent, hospitalNumber, recordTime);
        return R.success(list, "" + list.size());
    }


    @PostMapping("/list/data/save")
    @Operation(summary = "重症护理单数据保存")
    public R listOfDataSave(@RequestBody CareRecordDataVO careRecordDataVO) {
        if (!ContextUtil.getUserId().equals(careRecordDataVO.getUserId())) {
            return R.fail("该记录不是当前用户的记录");
        }

        Map<String, TimePlanInVO> result = bCareRecordsConfigNewService.listofDataSave(careRecordDataVO);
        if (result.containsKey("gcx")) {
            TimePlanInVO inVO = result.get("gcx");
            bTimePlanService.add(inVO);
            //同步自定义时间管理节点数据 需要与 ck库交互 暂时不做
            //ckPatientTimePointService.syncTimePoint(inVO.getModuleId(), inVO.getPatientIdent(), inVO.getHospitalNumber());
        } else {
            Long time = YDateUtils.strToDate(YDateUtils.format(new Date(careRecordDataVO.getRecordTime()),
                    YDateUtils.DATE_TIME_MINUTE_PATTERN) + ":00", YDateUtils.DATE_TIME_PATTERN).getTime();
            List<BTimePlan> yxTimePlanPOs = bTimePlanMapper.selectByTimeAndPAt(time, careRecordDataVO.getPatientIdent(), careRecordDataVO.getHospitalNumber(), "yx-gcx");
            if (CollectionUtil.isNotEmpty(yxTimePlanPOs)) {
                bTimePlanMapper.deleteByTimeAndPAt(time, careRecordDataVO.getPatientIdent(), careRecordDataVO.getHospitalNumber(), "yx-gcx");
            }
            //同步自定义时间管理节点数据 需要与 ck库交互 暂时不做
//            if (CollectionUtil.isNotEmpty(yxTimePlanPOs)) {
//                ckPatientTimePointService.syncTimePoint(yxTimePlanPOs.get(0).getModuleId(), yxTimePlanPOs.get(0).getPatientIdent(), yxTimePlanPOs.get(0).getHospitalNumber());
//            }
        }
        if (result.containsKey("hlcz")) {
            TimePlanInVO inVO = result.get("hlcz");
            bTimePlanService.add(inVO);
            //同步自定义时间管理节点数据 需要与 ck库交互 暂时不做
            //ckPatientTimePointService.syncTimePoint(inVO.getModuleId(), inVO.getPatientIdent(), inVO.getHospitalNumber());
        } else {
            Long time = YDateUtils.strToDate(YDateUtils.format(new Date(careRecordDataVO.getRecordTime()),
                    YDateUtils.DATE_TIME_MINUTE_PATTERN) + ":00", YDateUtils.DATE_TIME_PATTERN).getTime();
            List<BTimePlan> yxTimePlanPOs = bTimePlanMapper.selectByTimeAndPAt(time, careRecordDataVO.getPatientIdent(), careRecordDataVO.getHospitalNumber(), "yx-hlcz");
            if (CollectionUtil.isNotEmpty(yxTimePlanPOs)) {
                bTimePlanMapper.deleteByTimeAndPAt(time, careRecordDataVO.getPatientIdent(), careRecordDataVO.getHospitalNumber(), "hlcz");
            }
            //同步自定义时间管理节点数据 需要与 ck库交互 暂时不做
        // if (CollectionUtil.isNotEmpty(yxTimePlanPOs)) {
        // ckPatientTimePointService.syncTimePoint(yxTimePlanPOs.get(0).getModuleId(), yxTimePlanPOs.get(0).getPatientIdent(), yxTimePlanPOs.get(0).getHospitalNumber());
        //}
        }
        return R.success();
    }


    @GetMapping("/list/data/pgpf/one")
    @Operation(summary = "重症护理单评估评分模版数据/")
    public R<CartPgpfTempOutVO> listOfDataNewPgpfByTimeCode(@RequestParam String patientIdent, @RequestParam String hospitalNumber
            , @RequestParam Long recordTime, @RequestParam(required = false) Long rkTime) {

        CartPgpfTempOutVO list = bCareRecordsConfigNewService.listOfDataNewPgpfByTimeCode(patientIdent, hospitalNumber, recordTime, rkTime);
        return R.success(list);
    }


}


